<script lang="ts" setup>
import { ElMessageBox } from "element-plus";
import { activityType } from "@/config/dictionary";

import { templatePatternPageApi, getLabelPagerApi } from "@/api/activity";
import QrcodeVue from "qrcode.vue";

const router = useRouter(),
  store = useStore();

const searchForm = ref<any>({
  name: "",
  labelIds: [],
  showCount: 30,
  currentPage: 1,
}),
  searchStr = ref(""),
  filterType = ref("全部"),
  vagueSearch = ref(false),
  activityList = ref<Array<any>>([]),
  totalSize = ref<number | undefined>(undefined),
  loadFinish = ref(false),
  classifyList = ref<Array<any>>([]),
  classifyChildList = ref<Array<any>>([]),
  currentSelcetIndex = ref<number>(-1),
  layoutSpan = ref(6),
  complete = ref(false);

const adminType = store.state.user.adminType;
// const btnList = JSON.parse((sessionStorage as any).getItem("ACTIVITYBtn"));
const btnList = JSON.parse((localStorage as any).getItem("ACTIVITYBtn"));
const createPermission = (btnList || []).some((role: any) => role === "221");


const previewPath = `${(window as any).VUE_APP_URL[import.meta.env.MODE].activePreviewPath
  }${store.state.user.merchant.merchantCode}#/activity/preview/`;

const onKeyPress = (e: any) => {
  if (e.keyCode == 13) {
    console.log("按下回车键");
    searchName();
  }
};

const search = async (refresh: boolean = false) => {
  if (refresh) {
    searchForm.value.currentPage = 1;
    activityList.value = [];
    loadFinish.value = false;
  }
  const rs = await templatePatternPageApi({
    ...searchForm.value,
    labelIds: searchForm.value.labelIds.map((item: any) => {
      return [item];
    }),
  });
  if (rs.code == 200) {
    let page = (rs as any).page;
    if (page.currentPage >= page.totalPage) {
      loadFinish.value = true;
    }
    searchForm.value.currentPage = page.currentPage + 1;
    activityList.value = activityList.value.concat(rs.payload);
    totalSize.value = page.totalResult;
  }
};

const getLabelList = async () => {
  const rs = await getLabelPagerApi({ currentPage: 1, showCount: -1 });
  if (rs.code == 200) {
    classifyList.value = rs.payload;
  }
};

const changeType = (parent?: any, index: number | undefined = -1) => {
  if (currentSelcetIndex.value === index) {
    currentSelcetIndex.value = -2;
    return;
  }
  if (parent) {
    classifyChildList.value = parent.childLabels;
    currentSelcetIndex.value = index;
  } else {
    classifyChildList.value = [];
    searchForm.value.labelIds = [];
    currentSelcetIndex.value = -1;
    filterType.value = "全部";
    search(true);
  }
};

const searchName = () => {
  searchForm.value.name = searchStr.value;
  if (searchForm.value.name === "" || searchForm.value.name === undefined)
    vagueSearch.value = false;
  else vagueSearch.value = true;
  search(true);
};

const getSelectLabel = (labels: Array<any>) => {
  let label = labels.find(
    (item) => searchForm.value.labelIds.indexOf(item.id) >= 0
  );
  if (label) return true;
  return false;
};

const changeLabel = (label: any) => {
  searchForm.value.labelIds = [label.id];
  filterType.value = label.name;
  search(true);
};

const clearVagueSearch = () => {
  searchStr.value = "";
  searchName();
};

const openActivity = (activity: any) => {
  window.open(
    `${(window as any).VUE_APP_URL[import.meta.env.MODE].activePreviewPath
    }#/preview/${activity.component}?id=${activity.id}`
  );
};

const createActivity = (activity: any) => {
  if (adminType == 0 || createPermission) {
    router.push({ name: "ActivityAdd", params: { id: activity.id } });
  } else {
    ElMessageBox.alert("您没有权限创建活动，请联系管理员", "提示", {
      confirmButtonText: "我知道了",
    });
  }
};

const onresize = () => {
  if (document.body.clientWidth <= 1800) layoutSpan.value = 6;
  else layoutSpan.value = 4;
};
// 监听机构
const insId = computed(() => {
  return store.state.insId.insId;
});
watch(
  () => insId,
  () => { },
  {
    deep: true,
  }
);

onMounted(() => {
  onresize();
  window.onresize = onresize;
  getLabelList();
  search(true);
  nextTick(() => {
    complete.value = true;
  });
});

onBeforeUnmount(() => {
  window.onresize = null;
});
</script>
<script lang="ts">
export default {
  name: "ActivityHome",
};
</script>
<template>
  <el-affix :offset="60" style="width: 100%">
    <div class="content-header">
      <div class="content-title">首页</div>
    </div>
  </el-affix>
  <div class="container">
    <div class="banner">
      <div class="banner-item"></div>
      <div class="banner-search">
        <div class="search-container">
          <div class="search-inner">
            <el-input v-model="searchStr" placeholder="搜索活动名称" @keypress="onKeyPress" />
            <div class="search-icon" @click="searchName">
              <el-icon color="#909399" :size="18">
                <Search />
              </el-icon>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div v-if="vagueSearch" class="filter-bar2">
      <span @click="clearVagueSearch">{{ filterType }}</span> > 共找到与“{{
        searchForm.name
      }}”相关的活动{{ totalSize }}个
    </div>
    <div v-else class="filter-bar">
      <el-scrollbar>
        <div class="filter-level-1">
          <div class="filter-tag" :class="{
            active: searchForm.labelIds.length == 0,
          }" @click="changeType()">
            全部
          </div>
          <div v-for="(item, index) in classifyList" class="filter-tag" :class="{
            active: getSelectLabel(item.childLabels),
            expand: currentSelcetIndex == index,
          }" @click="changeType(item, index)">
            {{ item.name }}
            <el-icon v-if="currentSelcetIndex != index">
              <CaretBottom />
            </el-icon>
            <el-icon v-else>
              <CaretTop />
            </el-icon>
          </div>
        </div>
      </el-scrollbar>
      <el-scrollbar>
        <div class="filter-level-2" v-if="classifyChildList.length > 0 && currentSelcetIndex >= 0">
          <div v-for="item in classifyChildList" class="filter-tag" :class="{
            active: searchForm.labelIds.indexOf(item.id) >= 0,
          }" @click="changeLabel(item)">
            {{ item.name }}
          </div>
        </div>
      </el-scrollbar>
    </div>
    <template v-if="complete">
      <div class="activity" v-infinite-scroll="search" :infinite-scroll-distance="0"
        :infinite-scroll-disabled="loadFinish" :infinite-scroll-immediate="false">
        <el-row :gutter="20">
          <el-col :span="layoutSpan" v-for="item in activityList" style="margin-bottom: 10px">
            <el-card class="activity-item">
              <div class="activity-img">
                <div class="activity-img_container">
                  <img :src="item.cover" alt="" />
                  <div class="activity-qrcode">
                    <div class="qrcode-container">
                      <qrcode-vue :value="`${previewPath}${item.id}`" :size="120" level="H" />
                    </div>
                    <div>微信扫码体验活动</div>
                    <div class="footer">
                      <div v-has="['2023']" class="footer-item" @click="createActivity(item)">
                        <el-icon :size="16">
                          <Plus />
                        </el-icon>
                        <div style="margin-left: 4px;">创建</div>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
              <div class="activity-name">{{ item.name }}</div>
            </el-card>
          </el-col>
        </el-row>
      </div>
    </template>
    <el-empty v-if="activityList.length == 0" description="暂无数据" />
  </div>
</template>
<style lang="scss" scoped>
.content-header {
  padding-left: 30px;
  box-sizing: border-box;
  margin-bottom: 20px;
  height: 68px;
  line-height: 68px;
  font-size: 20px;
  background: #fff;
  display: flex;
  align-items: center;
  box-shadow: 0px 1px 12px 0px rgba(0, 0, 0, 0.06),
    inset 0px -1px 0px 0px #ebedf0;

  .content-title {
    font-weight: 700;
    color: #303133;
  }
}

.container {
  margin: 20px;

  .banner {
    position: relative;
    background: linear-gradient(to right, #306bf0 50%, #2789f0);

    .banner-item {
      background: url(@/assets/activity/home_banner1.jpg) no-repeat;
      background-position: center;
      background-size: auto 100%;
      overflow: hidden;
      height: 305px;
    }

    .banner-search {
      position: absolute;
      top: 32px;
      left: 50%;
      transform: translateX(-50%);

      .search-container {
        width: 412px;
        border: 5px solid rgba($color: #ffffff, $alpha: 0.28);
        border-radius: 32px;
        overflow: hidden;
      }

      .search-inner {
        background-color: #ffffff;
        padding-right: 20px;
        position: relative;

        :deep(.el-input__wrapper) {
          box-shadow: none;
        }

        .search-icon {
          cursor: pointer;
          padding-left: 10px;
          position: absolute;
          right: 15px;
          top: 50%;
          transform: translateY(-50%);
        }
      }
    }
  }

  .activity {
    .activity-item {
      :deep(.el-card__body) {
        padding: 0;
      }

      .activity-img {
        position: relative;
        overflow: hidden;
        height: 0;
        padding-bottom: 130%;
        cursor: pointer;

        &_container {
          position: absolute;
          top: 0;
          left: 0;
          width: 100%;
          height: 100%;

          >img {
            display: block;
            width: 100%;
          }

          .activity-qrcode {
            position: absolute;
            display: flex;
            justify-content: center;
            flex-direction: column;
            align-items: center;
            top: 100%;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba($color: #000000, $alpha: 0.4);
            color: #ffffff;
            transition: top 0.3s ease-out;

            .qrcode-container {
              background-color: #ffffff;
              padding: 5px;
              border-radius: 4px;
              margin-bottom: 10px;
            }

            .footer {
              position: absolute;
              bottom: 28px;
              left: 0;
              width: 100%;
              display: flex;
              align-items: center;
              justify-content: space-evenly;

              .footer-item {
                cursor: pointer;
                text-align: center;
                font-size: 14px;
                padding: 10px 36px;
                color: #666;
                background: #fff;
                border-radius: 24px;
                display: flex;
                align-items: center;
              }
            }
          }
        }

        &:hover {
          .activity-qrcode {
            top: 0;
          }
        }
      }

      .activity-name {
        overflow: hidden;
        text-overflow: ellipsis;
        padding: 10px 20px;
        text-align: center;
        font-size: 14px;
      }
    }
  }

  .filter-bar {
    margin-bottom: 20px;

    .filter-tag {
      user-select: none;
      flex-shrink: 0;
      padding: 0 30px;
      min-width: 98px;
      font-size: 14px;
      color: #606266;
      text-align: center;
      line-height: 54px;
      white-space: nowrap;
      box-sizing: border-box;
      cursor: pointer;
      border-left: 1px solid transparent;
      border-right: 1px solid transparent;

      &.active {
        color: #001e70;
        background-color: #f7f8fa !important;
      }
    }

    .filter-level-1 {
      border-bottom: 1px solid #dcdee0;
      height: 54px;
      display: flex;

      .filter-tag {
        &.expand {
          height: 55px;
          border-left: 1px solid #dcdee0;
          border-right: 1px solid #dcdee0;
          background-color: #ffffff;
        }
      }
    }

    .filter-level-2 {
      display: flex;
      border-bottom: 1px solid #dcdee0;
    }
  }

  .filter-bar2 {
    border-bottom: 1px solid #dcdee0;
    margin-bottom: 20px;
    font-size: 14px;
    color: #606266;
    line-height: 54px;
    padding-left: 40px;

    span {
      color: #001e70;
      cursor: pointer;
      user-select: none;
    }
  }
}
</style>
